package com.tanhua.admin.controller;

import cn.hutool.captcha.LineCaptcha;
import com.tanhua.admin.service.AdminService;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 生成验证码
     *
     * @param
     * @return void
     * @Author Pan Rundong
     */
    @GetMapping("/verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {
        // 1.调用工具类生成验证码
        LineCaptcha captcha = new LineCaptcha(300, 50);

        // 2.将验证码上传Redis
        redisTemplate.opsForValue().set(Constants.CAP_CODE + uuid, captcha.getCode());

        // 3.Http返回
        captcha.write(response.getOutputStream());
    }

    /**
     * 用户登录
     *
     * @param map
     * @return org.springframework.http.ResponseEntity
     * @Author Pan Rundong
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map) {
        Map resMap = null;
        try {
            resMap = adminService.login(map);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            return ResponseEntity.ok(resMap);
        }
    }

    /**
     * 获取用户资料
     *
     * @param
     * @return org.springframework.http.ResponseEntity<com.tanhua.model.vo.AdminVo>
     * @Author Pan Rundong
     */
    @PostMapping("/profile")
    public ResponseEntity<AdminVo> profile() {
        AdminVo vo = adminService.profile();
        return ResponseEntity.ok(vo);
    }
}
